package com.library.admin.handle;

import cn.hutool.json.JSONUtil;
import com.library.common.response.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 对认证过程中出现的异常进行特定的处理
 * 返回自定义未登录或者token失效时的结果：401错误信息
 *
 * @author: xyh
 * @create: 2023-10-02
 **/
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        Result result = Result.error(HttpServletResponse.SC_UNAUTHORIZED,"请求失败");

        if (authException instanceof InsufficientAuthenticationException) {
            result.setMsg("当前是未登录状态或token已经过期，请重新登录！");
        }
        outputStream.write(JSONUtil.toJsonStr(result).getBytes());
        outputStream.flush();
        outputStream.close();
    }

}
